<template>
  <a-layout style="min-height: 100vh; background: #f5f7fa;">
    <!-- 顶部导航 -->
    <nav-bar />

    <a-layout-content style="padding: 30px 50px; max-width: 1400px; margin: 0 auto; width: 100%;">
      <!-- 搜索区域 -->
      <a-card style="margin-bottom: 16px; border-radius: 8px; border: 1px solid #e4e7ed;">
        <a-space direction="vertical" style="width: 100%;" :size="16">
          <!-- 关键词搜索 -->
          <a-input-search
            v-model:value="searchQuery"
            :placeholder="$t('search.searchPlaceholder')"
            size="large"
            :enter-button="$t('search.searchButton')"
            @search="handleSearch"
          >
            <template #prefix>
              <search-outlined />
            </template>
          </a-input-search>

          <!-- 高级筛选 -->
          <a-space wrap>
            <a-auto-complete
              v-model:value="filters.species"
              :options="speciesSuggestions"
              :placeholder="$t('search.filterBySpecies')"
              style="width: 200px;"
              @search="handleSpeciesSearch"
              @select="handleSearch"
              @pressEnter="handleSearch"
              @focus="() => { if (!filters.species) handleSpeciesSearch('') }"
              allow-clear
            />
            <a-auto-complete
              v-model:value="filters.type"
              :options="typeSuggestions"
              :placeholder="$t('search.filterByType')"
              style="width: 200px;"
              @search="handleTypeSearch"
              @select="handleSearch"
              @pressEnter="handleSearch"
              @focus="() => { if (!filters.type) handleTypeSearch('') }"
              allow-clear
            />
            <a-button @click="resetFilters">{{ $t('search.resetButton') }}</a-button>
          </a-space>
        </a-space>
      </a-card>

      <!-- 推荐内容区域（搜索前显示） -->
      <div v-if="!hasSearched">
        <!-- 热门物种推荐 -->
        <a-card style="margin-bottom: 16px; border-radius: 8px; border: 1px solid #e4e7ed;">
          <template #title>
            <span style="font-size: 16px; color: #2c3e50; font-weight: 600;">
              {{ $t('search.popularSpecies') }}
            </span>
          </template>
          <div v-if="popularSpeciesLoading" style="text-align: center; padding: 20px;">
            <a-spin />
          </div>
          <div v-else-if="popularSpecies.length > 0" style="display: flex; flex-wrap: wrap; gap: 8px;">
            <a-tag
              v-for="species in popularSpecies"
              :key="species"
              color="blue"
              style="cursor: pointer; padding: 4px 12px; font-size: 14px;"
              @click="quickSearchSpecies(species)"
            >
              {{ species }}
            </a-tag>
          </div>
          <a-empty v-else :description="$t('search.noData')" :image="false" />
        </a-card>

        <!-- 热门类型推荐 -->
        <a-card style="margin-bottom: 16px; border-radius: 8px; border: 1px solid #e4e7ed;">
          <template #title>
            <span style="font-size: 16px; color: #2c3e50; font-weight: 600;">
              {{ $t('search.popularTypes') }}
            </span>
          </template>
          <div v-if="popularTypesLoading" style="text-align: center; padding: 20px;">
            <a-spin />
          </div>
          <div v-else-if="popularTypes.length > 0" style="display: flex; flex-wrap: wrap; gap: 8px;">
            <a-tag
              v-for="type in popularTypes"
              :key="type"
              color="green"
              style="cursor: pointer; padding: 4px 12px; font-size: 14px;"
              @click="quickSearchType(type)"
            >
              {{ type }}
            </a-tag>
          </div>
          <a-empty v-else :description="$t('search.noData')" :image="false" />
        </a-card>

        <!-- 数据统计 -->
        <a-card style="margin-bottom: 16px; border-radius: 8px; border: 1px solid #e4e7ed;">
          <template #title>
            <span style="font-size: 16px; color: #2c3e50; font-weight: 600;">
              {{ $t('search.statistics') }}
            </span>
          </template>
          <div v-if="statsLoading" style="text-align: center; padding: 20px;">
            <a-spin />
          </div>
          <a-row v-else :gutter="[16, 16]">
            <a-col :xs="24" :sm="12" :md="6">
              <a-statistic
                :title="$t('search.stats.proteins')"
                :value="stats.protein_count"
                :value-style="{ color: '#409eff' }"
              >
                <template #prefix>🧬</template>
              </a-statistic>
            </a-col>
            <a-col :xs="24" :sm="12" :md="6">
              <a-statistic
                :title="$t('search.stats.species')"
                :value="stats.species_count"
                :value-style="{ color: '#67c23a' }"
              >
                <template #prefix>🦠</template>
              </a-statistic>
            </a-col>
            <a-col :xs="24" :sm="12" :md="6">
              <a-statistic
                :title="$t('search.stats.structures')"
                :value="stats.pdb_file_count"
                :value-style="{ color: '#e6a23c' }"
              >
                <template #prefix>⚛️</template>
              </a-statistic>
            </a-col>
            <a-col :xs="24" :sm="12" :md="6">
              <a-statistic
                :title="$t('search.stats.imports')"
                :value="stats.import_count"
                :value-style="{ color: '#f56c6c' }"
              >
                <template #prefix>📊</template>
              </a-statistic>
            </a-col>
          </a-row>
        </a-card>

        <!-- 搜索历史 -->
        <a-card v-if="searchHistory.length > 0" style="border-radius: 8px; border: 1px solid #e4e7ed;">
          <template #title>
            <span style="font-size: 16px; color: #2c3e50; font-weight: 600;">
              {{ $t('search.recentSearches') }}
            </span>
          </template>
          <div style="display: flex; flex-wrap: wrap; gap: 8px;">
            <a-tag
              v-for="(item, index) in searchHistory"
              :key="index"
              color="default"
              style="cursor: pointer; padding: 4px 12px; font-size: 14px;"
              @click="quickSearchKeyword(item)"
              closable
              @close="removeSearchHistory(index)"
            >
              {{ item }}
            </a-tag>
          </div>
        </a-card>
      </div>

      <!-- 搜索结果（搜索后显示） -->
      <a-card v-if="hasSearched" style="border-radius: 8px; border: 1px solid #e4e7ed;">
        <template #title>
          <div style="display: flex; align-items: center; justify-content: space-between;">
            <span style="font-size: 16px; color: #2c3e50; font-weight: 600;">
              {{ $t('search.results') }} <a-tag v-if="total > 0">{{ $t('search.recordCount', { count: total }) }}</a-tag>
            </span>
            <a-button 
              type="primary" 
              :loading="downloading"
              @click="handleDownload"
              :disabled="total === 0"
            >
              <template #icon><download-outlined /></template>
              {{ $t('search.downloadCSV') }}
            </a-button>
          </div>
        </template>

        <!-- 空状态 -->
        <a-empty 
          v-if="!loading && proteins.length === 0" 
          :description="$t('search.noResults')"
          style="padding: 60px 0;"
        >
          <template #image>
            <div style="font-size: 64px; opacity: 0.3;">🔍</div>
          </template>
        </a-empty>

        <a-table
          v-else
          :dataSource="proteins"
          :columns="columns"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          row-key="id"
          :scroll="{ x: 1000 }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'species'">
              <a-tag>{{ record.species }}</a-tag>
            </template>

            <template v-else-if="column.key === 'type'">
              <a-tag>{{ record.type }}</a-tag>
            </template>

            <template v-else-if="column.key === 'accession'">
              <a-typography-text copyable>{{ record.accession }}</a-typography-text>
            </template>

            <template v-else-if="column.key === 'has_pdb'">
              <a-tag :color="record.has_pdb ? 'success' : 'default'">
                {{ record.has_pdb ? $t('search.table.available') : $t('search.table.unavailable') }}
              </a-tag>
            </template>

            <template v-else-if="column.key === 'action'">
              <router-link :to="`/protein/${record.id}`">
                <a-button type="primary" size="small">
                  <template #icon><eye-outlined /></template>
                  {{ $t('search.table.view') }}
                </a-button>
              </router-link>
            </template>
          </template>
        </a-table>
      </a-card>
    </a-layout-content>
  </a-layout>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { SearchOutlined, EyeOutlined, DownloadOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import axios from 'axios'
import config from '../config/env'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import NavBar from '../components/NavBar.vue'

const router = useRouter()
const route = useRoute()
const { t } = useI18n()
const searchQuery = ref('')
const loading = ref(false)
const downloading = ref(false)
const proteins = ref([])
const total = ref(0)
const hasSearched = ref(false) // 是否已执行搜索

// 推荐内容相关状态
const popularSpecies = ref([])
const popularTypes = ref([])
const popularSpeciesLoading = ref(false)
const popularTypesLoading = ref(false)
const stats = ref({
  protein_count: 0,
  species_count: 0,
  pdb_file_count: 0,
  import_count: 0
})
const statsLoading = ref(false)

// 搜索历史
const searchHistory = ref([])

const filters = reactive({
  species: '',
  type: ''
})

const speciesSuggestions = ref([])
const typeSuggestions = ref([])

const pagination = computed(() => ({
  current: paginationData.current,
  pageSize: paginationData.pageSize,
  total: paginationData.total,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => t('search.totalRecords', { count: total })
}))

const paginationData = reactive({
  current: 1,
  pageSize: 20,
  total: 0
})

const columns = computed(() => [
  {
    title: t('search.table.id'),
    dataIndex: 'id',
    key: 'id',
    width: 80,
    align: 'center'
  },
  {
    title: t('search.table.species'),
    dataIndex: 'species',
    key: 'species',
    width: 250,
    ellipsis: {
      showTitle: true
    },
    customRender: ({ text }) => {
      if (!text) return '-'
      // 如果超过30个字符，截断并显示...
      if (text.length > 30) {
        return text.substring(0, 30) + '...'
      }
      return text
    }
  },
  {
    title: t('search.table.accession'),
    dataIndex: 'accession',
    key: 'accession',
    width: 150
  },
  {
    title: t('search.table.type'),
    dataIndex: 'type',
    key: 'type',
    width: 120
  },
  {
    title: t('search.table.assembly'),
    dataIndex: 'assembly',
    key: 'assembly',
    width: 150,
    ellipsis: {
      showTitle: true
    }
  },
  {
    title: t('search.table.structure'),
    dataIndex: 'has_pdb',
    key: 'has_pdb',
    width: 100,
    align: 'center'
  },
  {
    title: t('search.table.action'),
    key: 'action',
    width: 120,
    fixed: 'right',
    align: 'center'
  }
])

const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      q: searchQuery.value,
      species: filters.species,
      type: filters.type,
      page: paginationData.current,
      page_size: paginationData.pageSize
    }

    const response = await axios.get(`${config.API_BASE_URL}/api/search/`, { params })
    proteins.value = response.data.data || []
    total.value = response.data.total || 0
    paginationData.total = response.data.total || 0
    
    // 同步URL参数
    syncUrlParams()
  } catch (error) {
    // 搜索失败时清空结果
    proteins.value = []
    total.value = 0
    paginationData.total = 0
    
    const errorMessage = error.response?.data?.detail || error.message || t('search.searchError')
    message.error(t('search.searchError') + ': ' + errorMessage)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  paginationData.current = 1
  hasSearched.value = true
  
  // 保存搜索历史
  if (searchQuery.value.trim()) {
    addToSearchHistory(searchQuery.value.trim())
  }
  
  fetchData()
}

const handleTableChange = (pag) => {
  paginationData.current = pag.current
  paginationData.pageSize = pag.pageSize
  
  // 如果改变pageSize，且当前页超出范围，重置到第1页
  const maxPage = Math.ceil(paginationData.total / pag.pageSize)
  if (pag.current > maxPage && maxPage > 0) {
    paginationData.current = 1
  }
  
  fetchData()
}

const handleSpeciesSearch = async (value) => {
  // 如果输入为空，显示常用选项（前10个）
  if (!value || value.trim() === '') {
    try {
      const response = await axios.get(`${config.API_BASE_URL}/autocomplete/`, {
        params: { field: 'species', q: '', limit: 10 }
      })
      speciesSuggestions.value = response.data.suggestions.map(s => ({ value: s }))
    } catch (error) {
      console.error('加载物种列表失败:', error)
    }
    return
  }
  
  // 输入至少1个字符时触发搜索
  try {
    const response = await axios.get(`${config.API_BASE_URL}/autocomplete/`, {
      params: { field: 'species', q: value.trim(), limit: 20 }
    })
    speciesSuggestions.value = response.data.suggestions.map(s => ({ value: s }))
  } catch (error) {
    console.error('自动补全失败:', error)
    // 出错时清空建议
    speciesSuggestions.value = []
  }
}

const handleTypeSearch = async (value) => {
  // 如果输入为空，显示常用选项（前10个）
  if (!value || value.trim() === '') {
    try {
      const response = await axios.get(`${config.API_BASE_URL}/autocomplete/`, {
        params: { field: 'type', q: '', limit: 10 }
      })
      typeSuggestions.value = response.data.suggestions.map(s => ({ value: s }))
    } catch (error) {
      console.error('加载类型列表失败:', error)
    }
    return
  }
  
  // 输入至少1个字符时触发搜索
  try {
    const response = await axios.get(`${config.API_BASE_URL}/autocomplete/`, {
      params: { field: 'type', q: value.trim(), limit: 20 }
    })
    typeSuggestions.value = response.data.suggestions.map(s => ({ value: s }))
  } catch (error) {
    console.error('自动补全失败:', error)
    // 出错时清空建议
    typeSuggestions.value = []
  }
}

const resetFilters = () => {
  searchQuery.value = ''
  filters.species = ''
  filters.type = ''
  hasSearched.value = false
  proteins.value = []
  total.value = 0
  paginationData.current = 1
  paginationData.total = 0
  // 清除URL参数
  router.replace({ path: '/search' })
}

const handleDownload = async () => {
  if (total.value === 0) {
    message.warning(t('search.noDataToDownload'))
    return
  }

  downloading.value = true
  try {
    const params = {
      q: searchQuery.value,
      species: filters.species,
      type: filters.type
    }

    const response = await axios.get(`${config.API_BASE_URL}/api/search/export/`, {
      params,
      responseType: 'blob'
    })

    // 创建下载链接
    const blob = new Blob([response.data], { type: 'text/csv;charset=utf-8;' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    // 从响应头获取文件名，如果没有则使用默认名称
    const contentDisposition = response.headers['content-disposition']
    let filename = `protein_search_results_${new Date().toISOString().split('T')[0]}.csv`
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename=(.+)/i)
      if (filenameMatch) {
        filename = decodeURIComponent(filenameMatch[1])
      }
    }
    
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    message.success(t('search.downloadSuccess'))
  } catch (error) {
    console.error('下载失败:', error)
    message.error(t('search.downloadError') + ': ' + (error.response?.data?.detail || error.message))
  } finally {
    downloading.value = false
  }
}

// 同步URL参数到搜索条件
const loadUrlParams = () => {
  const query = route.query
  if (query.q) searchQuery.value = query.q
  if (query.species) filters.species = query.species
  if (query.type) filters.type = query.type
  if (query.page) paginationData.current = parseInt(query.page) || 1
  if (query.pageSize) paginationData.pageSize = parseInt(query.pageSize) || 20
}

// 同步搜索条件到URL参数
const syncUrlParams = () => {
  const query = {
    ...route.query
  }
  
  // 更新或添加参数
  if (searchQuery.value) {
    query.q = searchQuery.value
  } else {
    delete query.q
  }
  
  if (filters.species) {
    query.species = filters.species
  } else {
    delete query.species
  }
  
  if (filters.type) {
    query.type = filters.type
  } else {
    delete query.type
  }
  
  if (paginationData.current > 1) {
    query.page = paginationData.current.toString()
  } else {
    delete query.page
  }
  
  if (paginationData.pageSize !== 20) {
    query.pageSize = paginationData.pageSize.toString()
  } else {
    delete query.pageSize
  }
  
  // 更新URL（不触发导航）
  router.replace({ query })
}

// 快速搜索函数
const quickSearchSpecies = (species) => {
  filters.species = species
  handleSearch()
}

const quickSearchType = (type) => {
  filters.type = type
  handleSearch()
}

const quickSearchKeyword = (keyword) => {
  searchQuery.value = keyword
  handleSearch()
}

// 搜索历史管理
const addToSearchHistory = (keyword) => {
  const history = searchHistory.value
  // 移除重复项
  const filtered = history.filter(item => item !== keyword)
  // 添加到开头，最多保留10条
  const updated = [keyword, ...filtered].slice(0, 10)
  searchHistory.value = updated
  localStorage.setItem('search_history', JSON.stringify(updated))
}

const removeSearchHistory = (index) => {
  searchHistory.value.splice(index, 1)
  localStorage.setItem('search_history', JSON.stringify(searchHistory.value))
}

const loadSearchHistory = () => {
  try {
    const saved = localStorage.getItem('search_history')
    if (saved) {
      searchHistory.value = JSON.parse(saved)
    }
  } catch (error) {
    console.error('加载搜索历史失败:', error)
  }
}

// 加载推荐内容
const loadPopularSpecies = async () => {
  popularSpeciesLoading.value = true
  try {
    const response = await axios.get(`${config.API_BASE_URL}/autocomplete/`, {
      params: { field: 'species', q: '', limit: 12 }
    })
    popularSpecies.value = response.data.suggestions || []
  } catch (error) {
    console.error('加载热门物种失败:', error)
  } finally {
    popularSpeciesLoading.value = false
  }
}

const loadPopularTypes = async () => {
  popularTypesLoading.value = true
  try {
    const response = await axios.get(`${config.API_BASE_URL}/autocomplete/`, {
      params: { field: 'type', q: '', limit: 12 }
    })
    popularTypes.value = response.data.suggestions || []
  } catch (error) {
    console.error('加载热门类型失败:', error)
  } finally {
    popularTypesLoading.value = false
  }
}

const loadStats = async () => {
  statsLoading.value = true
  try {
    const response = await axios.get(`${config.API_BASE_URL}/stats/`)
    stats.value = {
      protein_count: response.data.protein_count || 0,
      species_count: response.data.species_count || 0,
      pdb_file_count: response.data.pdb_file_count || 0,
      import_count: response.data.import_count || 0
    }
  } catch (error) {
    console.error('加载统计信息失败:', error)
  } finally {
    statsLoading.value = false
  }
}

onMounted(() => {
  // 从URL加载参数
  loadUrlParams()
  
  // 加载搜索历史
  loadSearchHistory()
  
  // 加载推荐内容
  loadPopularSpecies()
  loadPopularTypes()
  loadStats()
  
  // 判断是否应该自动搜索（URL有参数）
  const shouldAutoSearch = route.query.q || route.query.species || route.query.type
  if (shouldAutoSearch) {
    hasSearched.value = true
    fetchData()
  }
})
</script>

<style scoped>
:deep(.ant-menu-item) {
  font-weight: 500;
  color: #606266;
}

:deep(.ant-menu-item-selected) {
  color: #409eff !important;
  font-weight: 600;
}

:deep(.ant-menu-item-selected::after) {
  border-bottom-color: #409eff !important;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  color: #2c3e50;
  font-weight: 600;
}

:deep(.ant-btn-primary) {
  background: #409eff;
  border-color: #409eff;
}
</style>